const Setting = require('../models/Setting');
const { successResponse, errorResponse } = require('../utils/response');
const logger = require('../utils/logger');

// 获取所有设置
exports.getSettings = async (req, res) => {
  try {
    // 查询条件
    const filter = {};
    if (req.query.category) {
      filter.category = req.query.category;
    }

    const settings = await Setting.find(filter).sort({ key: 1 });
    
    // 将设置转换为对象格式
    const settingsObject = {};
    settings.forEach(setting => {
      settingsObject[setting.key] = {
        value: setting.value,
        description: setting.description,
        category: setting.category,
        updatedAt: setting.updatedAt
      };
    });

    return successResponse(res, settingsObject, '获取设置成功');
  } catch (error) {
    logger.error(`获取设置列表失败: ${error.message}`);
    return errorResponse(res, '获取设置列表失败', 500);
  }
};

// 获取单个设置
exports.getSetting = async (req, res) => {
  try {
    const setting = await Setting.findOne({ key: req.params.key });
    
    if (!setting) {
      return errorResponse(res, '设置不存在', 404);
    }

    return successResponse(res, setting, '获取设置成功');
  } catch (error) {
    logger.error(`获取设置失败: ${error.message}`);
    return errorResponse(res, '获取设置失败', 500);
  }
};

// 更新或创建设置
exports.updateSetting = async (req, res) => {
  try {
    const { value, description, category } = req.body;
    const key = req.params.key;

    // 查找现有设置
    let setting = await Setting.findOne({ key });
    
    if (setting) {
      // 更新现有设置
      setting.value = value;
      if (description) setting.description = description;
      if (category) setting.category = category;
      setting.updatedAt = Date.now();
      
      await setting.save();
      return successResponse(res, setting, '更新设置成功');
    } else {
      // 创建新设置
      setting = new Setting({
        key,
        value,
        description: description || '',
        category: category || 'general'
      });
      
      await setting.save();
      return successResponse(res, setting, '创建设置成功', 201);
    }
  } catch (error) {
    logger.error(`更新设置失败: ${error.message}`);
    return errorResponse(res, '更新设置失败', 500);
  }
};

// 删除设置
exports.deleteSetting = async (req, res) => {
  try {
    const setting = await Setting.findOne({ key: req.params.key });
    
    if (!setting) {
      return errorResponse(res, '设置不存在', 404);
    }

    await setting.remove();
    return successResponse(res, null, '删除设置成功');
  } catch (error) {
    logger.error(`删除设置失败: ${error.message}`);
    return errorResponse(res, '删除设置失败', 500);
  }
}; 